﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace Microsoft.SocialRecipes
{
    /// <summary>
    /// Custom control to display HTML 5 Video Player
    /// </summary>
    public class HTML5VideoFieldControl : BaseFieldControl
    {

        //Controls
        protected TextBox txtVideoUrl;
        protected TextBox txtWidth;
        protected TextBox txtHeight;
        protected CheckBox chkShowMediaControlsOnDisplay;
        protected TextBox txtContentType;
        protected SPFieldHTML5VideoPlayerValue fieldValue;
        protected TextBox txtAssociatedJavaScriptUrl;
        protected TextBox txtThumbnailUrl;
               
        /// <summary>
        /// Gets the name of the default rendering template.
        /// </summary>
        /// <returns>A <see cref="T:System.String"/> object that names a rendering template. </returns>
        protected override string DefaultTemplateName
        {
            get
            {
                return Constants.CustomRenderingTemplate;
            }
        }


        /// <summary>
        /// When overridden in a derived class, gets or sets the value of the field in the UI.
        /// </summary>
        /// <returns>When overridden in a derived class, a <see cref="T:System.Object"/> that represents the value of the field in the UI. Typically, this is the text of a child control, such as a label or text box, that actually renders the field. </returns>
        public override object Value
        {
            get
            {
                EnsureChildControls();
                fieldValue = new SPFieldHTML5VideoPlayerValue();
                fieldValue.VideoUrl = txtVideoUrl.Text.Trim();
                fieldValue.Height = txtHeight.Text.Trim();
                fieldValue.Width = txtWidth.Text.Trim();
                fieldValue.ShowMediaControlsOnDisplay = chkShowMediaControlsOnDisplay.Checked;
                fieldValue.ContentType = txtContentType.Text.Trim();
                fieldValue.AssociatedJavaScriptUrl = txtAssociatedJavaScriptUrl.Text.Trim();
                fieldValue.ThumbnailUrl = txtThumbnailUrl.Text.Trim();
                return fieldValue;
            }
            set
            {
                EnsureChildControls();
                fieldValue = value as SPFieldHTML5VideoPlayerValue;
                txtVideoUrl.Text = fieldValue.VideoUrl;
                txtHeight.Text = fieldValue.Height;
                txtWidth.Text = fieldValue.Width;
                txtContentType.Text = fieldValue.ContentType;
                chkShowMediaControlsOnDisplay.Checked = fieldValue.ShowMediaControlsOnDisplay;
                txtAssociatedJavaScriptUrl.Text = fieldValue.AssociatedJavaScriptUrl;
                txtThumbnailUrl.Text = fieldValue.ThumbnailUrl;
            }
        }

        /// <summary>
        /// Represents the method that handles the <see cref="E:System.Web.UI.Control.PreRender"/> event of a <see cref="T:Microsoft.SharePoint.WebControls.FieldMetadata"/> object.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (ControlMode == SPControlMode.Display)
            {
                if (txtAssociatedJavaScriptUrl != null && !string.IsNullOrEmpty(txtAssociatedJavaScriptUrl.Text))
                {
                    ClientScriptManager scriptManager = Page.ClientScript;
                    if (!scriptManager.IsClientScriptIncludeRegistered(typeof(Page), Constants.AssociatedJavaScriptKey))
                    {
                        scriptManager.RegisterClientScriptInclude(typeof(Page), Constants.AssociatedJavaScriptKey, txtAssociatedJavaScriptUrl.Text.Trim());
                    }
                }
            }
        }

        
        /// <summary>
        /// Creates any child controls necessary to render the field, such as a label control, link control, or text box control.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (base.IsFieldValueCached || Field == null)
            {
                return;
            }

            // Decide rendering
            switch (ControlMode)
            {
                case SPControlMode.Display:
                    break;
                case SPControlMode.Edit:
                case SPControlMode.New:
                    PopulateControls(TemplateContainer);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// When overridden in a derived class, verifies that the value of <see cref="P:Microsoft.SharePoint.WebControls.BaseFieldControl.Value"/> meets all restrictions on field content such as length, format, and data type.
        /// </summary>
        public override void Validate()
        {            
            if (base.ControlMode == SPControlMode.Display || !base.IsValid || !this.Visible)
            {
                return;
            }
            
            if (fieldValue == null)
            {
                return;
            }

            base.Validate();

            // Validte Required Fields
            if (string.IsNullOrEmpty(fieldValue.VideoUrl))
            {
                base.ErrorMessage = "Video Url is required.";
                base.IsValid = false;
                return;
            }            

            if (string.IsNullOrEmpty(fieldValue.Width))
            {
                fieldValue.Width = "300";
            }

            if (string.IsNullOrEmpty(fieldValue.Height))
            {
                fieldValue.Width = "300";
            }

            base.IsValid = true;
        }

        /// <summary>
        /// Renders the field on the page.
        /// </summary>
        /// <param name="output">The object that writes the HTML that is to be rendered.</param>
        protected override void Render(HtmlTextWriter output)
        {
            base.Render(output);

            fieldValue = this.ListItemFieldValue as SPFieldHTML5VideoPlayerValue;
            if (fieldValue == null)
            {
                return;
            }

            if (base.ControlMode == SPControlMode.Display)
            {
                string controls = fieldValue.ShowMediaControlsOnDisplay == true ? "controls": string.Empty;
             
                // Write the HTML5 video tag so it gets rendered when the page is in display mode.
                var html5VideoString = string.Format(Constants.HTML5VideoTag, fieldValue.Width, fieldValue.Height, controls, fieldValue.VideoUrl, fieldValue.ContentType, fieldValue.ThumbnailUrl);                
                output.WriteLine(html5VideoString);  
            }
        }

        /// <summary>
        /// Populates the controls.
        /// </summary>
        /// <param name="container">The container.</param>
        private void PopulateControls(TemplateContainer container)
        {
            // Get the values for the fields from the User Control
            txtVideoUrl = container.FindControl(Constants.VideoUrlControlName) as TextBox;
            txtHeight = container.FindControl(Constants.HeightControlName) as TextBox;
            txtWidth = container.FindControl(Constants.HeightControlName) as TextBox;
            txtContentType = container.FindControl(Constants.ContentTypeControlName) as TextBox;
            txtAssociatedJavaScriptUrl = container.FindControl(Constants.AssociatedJavaScriptUrlName) as TextBox;
            txtThumbnailUrl = container.FindControl(Constants.ThumbnailUrlName) as TextBox;
            chkShowMediaControlsOnDisplay = container.FindControl(Constants.ShowMediaControlsOnDisplayControlName) as CheckBox;
        }
    }
}
